from forest.resource import Resources, Resource, ValidationError
import os
import fnmatch

class DiskNameMapping(Resource):
    ''' Creates an alias name for disks matching a pattern.

        Example::

            resources:
              - $: disk-name
                name: disk1
                mapping: "[vhs]da"

        .. describe:: name

            Alias for the disk.

        .. describe:: mapping

            A pattern, matching the possible physical disk names aliased by the
            disk name. Devices are searched for in the /dev directory.

    '''
    __register__ = "disk-name"

    def get_device(self):
        matches =  fnmatch.filter(os.listdir('/dev'), self.value.get('mapping'))

        if not matches:
            raise Exception("Disk does not exist matching %s" % self.value.get('mapping'))

        return matches[0]

    def get_name(self):
        return self.value.get('name')

    def get_id(self):
        return 'disk-name:'+self.value.get('name')
